package com.wash.shoes.domain.dy.request;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wash.shoes.common.enums.WriteOffStatusEnum;
import com.wash.shoes.domain.dy.model.DyServiceUpdateResp;
import com.wash.shoes.domain.dy.model.ServiceUpdateDto;
import com.wash.shoes.entity.BrandPo;
import com.wash.shoes.entity.OrderGoodPo;
import com.wash.shoes.entity.OrderPo;
import com.wash.shoes.entity.OrderTransportPo;
import com.wash.shoes.mapper.OrderGoodMapper;
import com.wash.shoes.service.BrandService;
import com.wash.shoes.service.OrderTransportService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lijianguo
 * @Date 01/04/2025 14:10 https://bytedance.larkoffice.com/docx/YklZdtg5poKToUx0uD9cLjWtnEd 洗护服务状态更新
 **/
@Log4j2
@Component
public class DyServiceUpdateRequest extends DyBaseRequest {

    @Resource
    OrderTransportService orderTransportService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private OrderGoodMapper orderGoodMapper;

    /**
     * @param orderPo 订单的信息-只处理都应的订单 更新状态
     * @return 处理信息 1 -- 已寄出（已取件）2 -- 洗护完成 3 -- 已寄回 4 -- 服务完成
     */
    public String updateFullFill(OrderPo orderPo, Integer status) {

        log.info("dy FullFill {}  status {}", orderPo.getFulfillStatus(), status);
        // 只是处理抖音的订单的洗护状态
        if (!orderPo.getComeFrom().equals("3")) {
            return null;
        }
        if (StrUtil.isNotBlank(orderPo.getFulfillStatus())) {
            int curStatus = Integer.parseInt(orderPo.getFulfillStatus());
            // 如果在下一阶段就不处理
            if (curStatus >= status) {
                log.info("in next step dont process");
                return "success";
            }
        }
        List<OrderGoodPo> data = orderGoodMapper.selectList(new LambdaQueryWrapper<OrderGoodPo>().eq(OrderGoodPo::getOrderId, orderPo.getId()));

        // 核销的时候修改为取对应品牌的id去核销
        BrandPo brandPo = brandService.getById(orderPo.getBrandId());
        Assert.notNull(brandPo, "品牌信息未找到数据异常,brandId:" + orderPo.getBrandId());
        List<DyServiceUpdateResp> dyServiceUpdateResps = new ArrayList<>();
        final StringBuilder result = new StringBuilder();
        //新预约
        if (orderPo.isNewBook()) {
            data.forEach(orderGoodPo -> {
                result.setLength(0);
                ServiceUpdateDto serviceUpdateDto = new ServiceUpdateDto();
                serviceUpdateDto.setAccount_id(brandPo.getAccountid());
                // 核销的时候修改为取对应品牌的id去核销
                serviceUpdateDto.setOrder_id(orderPo.getMtOrderId());
                serviceUpdateDto.setBook_id(orderPo.isNewBook() ? orderGoodPo.getDyBookId() : orderPo.getDyBookId());
                serviceUpdateDto.setService_status(status);
                serviceUpdateDto.setAction_time((int) (System.currentTimeMillis() / 1000));
                if (serviceUpdateDto.getService_status() == 1 || serviceUpdateDto.getService_status() == 3) {
                    OrderTransportPo orderTransportPo;
                    if (serviceUpdateDto.getService_status() == 1) {
                        orderTransportPo = orderTransportService.getOneByOrderIdType(orderPo.getId(), "取鞋");
                    } else {
                        orderTransportPo = orderTransportService.getOneByOrderIdType(orderPo.getId(), "送鞋");
                        if (orderTransportPo == null) {
                            orderTransportPo = orderTransportService.getOneByOrderIdType(orderPo.getId(), "取鞋");
                        }
                        // 最后一个
                        if (orderTransportPo == null) {
                            orderTransportPo = orderTransportService.getLastTransport();
                        }
                    }
                    ServiceUpdateDto.LogisticsInfo logisticsInfo = new ServiceUpdateDto.LogisticsInfo();
                    logisticsInfo.setExpress_no(DyConstant.EXPRESS_COMPANY);
                    logisticsInfo.setTrack_no(orderTransportPo.getWayBillCode());
                    serviceUpdateDto.setLogistics_info(logisticsInfo);

                }
                String result1 = postRequest(DyConstant.SERVICE_UPDATE_POST, serviceUpdateDto, brandPo.getAccountid());
                JSONObject jsonObject = JSONObject.parseObject(result1);
                result.append(result1);
                JSONObject extra = jsonObject.getJSONObject("extra");
                Integer errorCode = extra.getInteger("error_code");
                Integer sub_error_code = extra.getInteger("sub_error_code");

                dyServiceUpdateResps.add(DyServiceUpdateResp.builder().sub_error_code(sub_error_code).errorCode(errorCode).build());
            });
        } else {
            //老预约
            ServiceUpdateDto serviceUpdateDto = new ServiceUpdateDto();
            serviceUpdateDto.setAccount_id(brandPo.getAccountid());
            // 核销的时候修改为取对应品牌的id去核销
            serviceUpdateDto.setOrder_id(orderPo.getMtOrderId());
            serviceUpdateDto.setBook_id(orderPo.getDyBookId());
            serviceUpdateDto.setService_status(status);
            serviceUpdateDto.setAction_time((int) (System.currentTimeMillis() / 1000));
            if (serviceUpdateDto.getService_status() == 1 || serviceUpdateDto.getService_status() == 3) {
                OrderTransportPo orderTransportPo;
                if (serviceUpdateDto.getService_status() == 1) {
                    orderTransportPo = orderTransportService.getOneByOrderIdType(orderPo.getId(), "取鞋");
                } else {
                    orderTransportPo = orderTransportService.getOneByOrderIdType(orderPo.getId(), "送鞋");
                    if (orderTransportPo == null) {
                        orderTransportPo = orderTransportService.getOneByOrderIdType(orderPo.getId(), "取鞋");
                    }
                    // 最后一个
                    if (orderTransportPo == null) {
                        orderTransportPo = orderTransportService.getLastTransport();
                    }
                }
                ServiceUpdateDto.LogisticsInfo logisticsInfo = new ServiceUpdateDto.LogisticsInfo();
                logisticsInfo.setExpress_no(DyConstant.EXPRESS_COMPANY);
                logisticsInfo.setTrack_no(orderTransportPo.getWayBillCode());
                serviceUpdateDto.setLogistics_info(logisticsInfo);

            }
            String result1 = postRequest(DyConstant.SERVICE_UPDATE_POST, serviceUpdateDto, brandPo.getAccountid());
            JSONObject jsonObject = JSONObject.parseObject(result1);
            JSONObject extra = jsonObject.getJSONObject("extra");
            Integer errorCode = extra.getInteger("error_code");
            Integer sub_error_code = extra.getInteger("sub_error_code");
            dyServiceUpdateResps.add(DyServiceUpdateResp.builder().sub_error_code(sub_error_code).errorCode(errorCode).build());
        }

        //全部核销成功才
        List<Integer> resultCode = dyServiceUpdateResps.stream().map(DyServiceUpdateResp::getErrorCode).distinct().collect(Collectors.toList());
        //判断返回的code是否全部为0
        boolean f1 = resultCode.stream().allMatch(f -> f == (0));
        //表示查不到子预约单，用户可能退款，这里处理这种异常情况,虽然也有定时任务在处理，这里在兼容一下，核销完成
        boolean f2 = resultCode.stream().anyMatch(f -> f == (2033002155));
        //用户已核销
        boolean f3 = resultCode.stream().anyMatch(f -> f == (2033002157));
        //核销成功
        if (f1) {
            orderPo.setFulfillStatus(String.valueOf(status));
            //是服务完成 的
            if (4 == status) {
                //设置核销状态
                orderPo.setWriteOffStatus(WriteOffStatusEnum.WRITE_OFF);
            }
            //设置抖音核销完成时间,status是表示物流已揽收 不用更新核销时间
            if (status != 1 && status != 2) {
                orderPo.setDyVerificationTime(new Date());
            }
            orderService.updateById(orderPo);
        }
        if (f2) {
            //表示查不到子预约单，用户可能退款，这里处理这种异常情况
            //虽然也有定时任务在处理，这里在兼容一下，核销完成
            orderPo.setDyVerificationTime(new Date());
            orderPo.setExtendInfo("用户已退款或者已经取消");
            orderService.updateById(orderPo);
        }
        if (f3) {
            //用户已核销
            orderPo.setDyVerificationTime(new Date());
            orderService.updateById(orderPo);
        }
        // {"extra":{"error_code":0,"description":"success","sub_error_code":0,"sub_description":"","logid":"20250401144901F19B5BBB56EB1F059CC1","now":1743490141},"data":{"error_code":0,"description":"success"}}
        return result.toString();
    }
}
